package com.xywy.beautyand.util;

import java.io.File;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;

/**
* �ϴ�ͼƬ
* @author dance
* 
*/
public class HttpClientUploadTask implements Runnable{

	private Handler handler;
	private String url;
	private String filepath;
	private String button;

	/**
	 * @param handler
	 *           handler
	 * @param mapParams
	 *          
	 */
	public HttpClientUploadTask(String url,Handler handler, String filepath,String button)
			  {
		this.handler = handler;
		this.filepath=filepath;
		this.url=url;
		this.button=button;
	}

	public interface HttpClientUploadResponse {
		int FAIL = 0;
		int SUCESS=1;
		int ERROR=500;
	}

	@Override
	public void run() {
			
		HttpPost postRequest = new HttpPost(url);
		MultipartEntity reqEntity = new MultipartEntity();
		reqEntity.addPart("file",new FileBody(new File(filepath))); 
		try {
			reqEntity.addPart("button",new StringBody("submit"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		postRequest.setEntity(reqEntity);  
		HttpClient httpclient = new DefaultHttpClient();  
		//
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
		//
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
		HttpResponse response = null;   
		try {
			Message message = handler.obtainMessage();
			response = httpclient.execute(postRequest);
			int _sucess_status =response.getStatusLine().getStatusCode();
			System.out.println("........0.."+_sucess_status);
			if(_sucess_status==200){
			String str = EntityUtils.toString(response.getEntity(), "UTF-8");
			//
			System.out.println("返回结果|||"+str);
			JSONObject object=new JSONObject(str);
			int status=object.optInt("status");// 
			String data=object.optString("data");//
			String  messages=object.optString("message");//
			
			if(status==2){
				message.what = HttpClientUploadResponse.SUCESS;
				message.obj = data;
			}
			else {
				message.what = HttpClientUploadResponse.ERROR;
				message.obj = messages;//
				
			}
			}else{
				message.what = HttpClientUploadResponse.FAIL;
			}
			handler.sendMessage(message);
		}  catch (Exception e) {
			e.printStackTrace();
			Message message = handler.obtainMessage();
			message.what = HttpClientUploadResponse.FAIL;
		    handler.sendMessage(message);
		}   
	}
}
